import 'package:mobx/mobx.dart';
import 'package:thal/backstage/blueprint/single_chat_print.dart';

part 'single_chat_room.g.dart';

/// 单聊状态管理
class SingleChatRoom = _SingleChatRoom with _$SingleChatRoom;

abstract class _SingleChatRoom with Store {
  /// 单聊列表
  @observable
  ObservableList<SingleChatPrint> singleChats =
      ObservableList<SingleChatPrint>();

  /// 单聊消息列表
  @observable
  ObservableList<SingleChatMessagePrint> singleMessages =
      ObservableList<SingleChatMessagePrint>();

  /// 初始化默认单聊数据
  @action
  void initializeDefaultSingleChats() {
    singleChats = ObservableList<SingleChatPrint>.of([
      // admin 与 waterlover 的单聊
      SingleChatPrint(
        id: '1',
        userId1: '1', // admin
        userId2: '2', // waterlover
        createdAt: DateTime.now().subtract(const Duration(days: 5)),
      ),
      // admin 与 lakephoto 的单聊
      SingleChatPrint(
        id: '2',
        userId1: '1', // admin
        userId2: '3', // lakephoto
        createdAt: DateTime.now().subtract(const Duration(days: 4)),
      ),
      // admin 与 naturefan 的单聊
      SingleChatPrint(
        id: '3',
        userId1: '1', // admin
        userId2: '4', // naturefan
        createdAt: DateTime.now().subtract(const Duration(days: 3)),
      ),
      // admin 与 lakeexplorer 的单聊
      SingleChatPrint(
        id: '4',
        userId1: '1', // admin
        userId2: '5', // lakeexplorer
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
      ),
    ]);

    // 初始化默认消息数据
    singleMessages = ObservableList<SingleChatMessagePrint>.of([
      // admin 与 waterlover 的聊天记录
      SingleChatMessagePrint(
        id: '1',
        chatId: '1',
        senderId: '1', // admin
        messageType: 'text',
        content:
            'Hey! I saw your amazing Lake Tahoe photos. The sunset looks incredible!',
        createdAt: DateTime.now().subtract(const Duration(days: 5)),
      ),
      SingleChatMessagePrint(
        id: '2',
        chatId: '1',
        senderId: '2', // waterlover
        messageType: 'text',
        content:
            'Thank you! Lake Tahoe never disappoints. Have you been there recently?',
        createdAt: DateTime.now().subtract(const Duration(days: 4)),
      ),
      SingleChatMessagePrint(
        id: '3',
        chatId: '1',
        senderId: '1', // admin
        messageType: 'call_failed',
        content: 'Call failed - User busy',
        createdAt: DateTime.now().subtract(const Duration(days: 3)),
      ),
      SingleChatMessagePrint(
        id: '4',
        chatId: '1',
        senderId: '2', // waterlover
        messageType: 'text',
        content:
            'Sorry about the call! I was hiking around Lake Como. The signal is terrible there.',
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
      ),

      // admin 与 lakephoto 的聊天记录
      SingleChatMessagePrint(
        id: '5',
        chatId: '2',
        senderId: '3', // lakephoto
        messageType: 'text',
        content:
            'Hi admin! I just captured some stunning aerial shots of Crater Lake. Want to see them?',
        createdAt: DateTime.now().subtract(const Duration(days: 4)),
      ),
      SingleChatMessagePrint(
        id: '6',
        chatId: '2',
        senderId: '1', // admin
        messageType: 'text',
        content:
            'Absolutely! Your photography skills are amazing. Crater Lake is such a photogenic place.',
        createdAt: DateTime.now().subtract(const Duration(days: 3)),
      ),
      SingleChatMessagePrint(
        id: '7',
        chatId: '2',
        senderId: '1', // admin
        messageType: 'call_failed',
        content: 'Call failed - User busy',
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
      ),
      SingleChatMessagePrint(
        id: '8',
        chatId: '2',
        senderId: '3', // lakephoto
        messageType: 'text',
        content:
            'Sorry I missed your call! I was editing photos from my Lake Baikal trip.',
        createdAt: DateTime.now().subtract(const Duration(days: 1)),
      ),

      // admin 与 naturefan 的聊天记录
      SingleChatMessagePrint(
        id: '9',
        chatId: '3',
        senderId: '1', // admin
        messageType: 'text',
        content:
            'I love your posts about hidden lakes! Where do you find these amazing spots?',
        createdAt: DateTime.now().subtract(const Duration(days: 3)),
      ),
      SingleChatMessagePrint(
        id: '10',
        chatId: '3',
        senderId: '4', // naturefan
        messageType: 'text',
        content:
            'Thanks! I spend a lot of time exploring off-the-beaten-path locations. Nature always surprises me.',
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
      ),
      SingleChatMessagePrint(
        id: '11',
        chatId: '3',
        senderId: '4', // naturefan
        messageType: 'call_failed',
        content: 'Call failed - No answer',
        createdAt: DateTime.now().subtract(const Duration(hours: 6)),
      ),
      SingleChatMessagePrint(
        id: '12',
        chatId: '3',
        senderId: '1', // admin
        messageType: 'text',
        content:
            'Sorry I missed your call! I was at Lake Como enjoying the sunset. Let\'s chat tomorrow!',
        createdAt: DateTime.now().subtract(const Duration(hours: 3)),
      ),

      // admin 与 lakeexplorer 的聊天记录
      SingleChatMessagePrint(
        id: '13',
        chatId: '4',
        senderId: '5', // lakeexplorer
        messageType: 'text',
        content:
            'Hey admin! I\'m planning a lake exploration trip next month. Any recommendations?',
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
      ),
      SingleChatMessagePrint(
        id: '14',
        chatId: '4',
        senderId: '1', // admin
        messageType: 'text',
        content:
            'That sounds exciting! I\'d recommend Lake Baikal and Crater Lake. Both are absolutely stunning.',
        createdAt: DateTime.now().subtract(const Duration(days: 1)),
      ),
      SingleChatMessagePrint(
        id: '15',
        chatId: '4',
        senderId: '1', // admin
        messageType: 'call_failed',
        content: 'Call failed - User busy',
        createdAt: DateTime.now().subtract(const Duration(hours: 12)),
      ),
      SingleChatMessagePrint(
        id: '16',
        chatId: '4',
        senderId: '5', // lakeexplorer
        messageType: 'text',
        content:
            'Thanks for the suggestions! I\'ll definitely check out those lakes. The call failed because I was in a remote area.',
        createdAt: DateTime.now().subtract(const Duration(hours: 8)),
      ),
    ]);
  }

  /// 获取所有单聊
  List<SingleChatPrint> fetchAllSingleChats() {
    return List.from(singleChats);
  }

  /// 根据ID获取单聊
  SingleChatPrint? fetchSingleChatById(String id) {
    try {
      return singleChats.firstWhere((chat) => chat.id == id);
    } catch (e) {
      return null;
    }
  }

  /// 获取用户的所有单聊
  List<SingleChatPrint> fetchUserSingleChats(String userId) {
    return singleChats
        .where((chat) => chat.userId1 == userId || chat.userId2 == userId)
        .toList();
  }

  /// 获取两个用户之间的单聊
  SingleChatPrint? fetchSingleChatBetweenUsers(String userId1, String userId2) {
    try {
      return singleChats.firstWhere(
        (chat) =>
            (chat.userId1 == userId1 && chat.userId2 == userId2) ||
            (chat.userId1 == userId2 && chat.userId2 == userId1),
      );
    } catch (e) {
      return null;
    }
  }

  /// 获取单聊的所有消息
  List<SingleChatMessagePrint> fetchSingleChatMessages(String chatId) {
    return singleMessages.where((message) => message.chatId == chatId).toList()
      ..sort((a, b) => a.createdAt.compareTo(b.createdAt)); // 按时间排序
  }

  /// 获取单聊的最新消息
  SingleChatMessagePrint? fetchLatestSingleChatMessage(String chatId) {
    final messages = fetchSingleChatMessages(chatId);
    return messages.isNotEmpty ? messages.last : null;
  }

  /// 创建单聊
  @action
  String createSingleChat(String userId1, String userId2) {
    try {
      // 检查是否已存在单聊
      final existingChat = fetchSingleChatBetweenUsers(userId1, userId2);
      if (existingChat != null) {
        return existingChat.id;
      }

      final newChat = SingleChatPrint(
        id: (singleChats.length + 1).toString(),
        userId1: userId1,
        userId2: userId2,
        createdAt: DateTime.now(),
      );
      singleChats.add(newChat);
      return newChat.id;
    } catch (e) {
      return '';
    }
  }

  /// 发送文本消息
  @action
  bool sendTextMessage(String chatId, String senderId, String content) {
    try {
      final newMessage = SingleChatMessagePrint(
        id: '${DateTime.now().millisecondsSinceEpoch}',
        chatId: chatId,
        senderId: senderId,
        messageType: 'text',
        content: content,
        createdAt: DateTime.now(),
      );
      singleMessages.add(newMessage);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 发送拨打失败消息
  @action
  bool sendCallFailedMessage(String chatId, String senderId, String reason) {
    try {
      final newMessage = SingleChatMessagePrint(
        id: '${DateTime.now().millisecondsSinceEpoch}',
        chatId: chatId,
        senderId: senderId,
        messageType: 'call_failed',
        content: 'Call failed - $reason',
        createdAt: DateTime.now(),
      );
      singleMessages.add(newMessage);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 获取单聊消息数量
  int getSingleChatMessageCount(String chatId) {
    return singleMessages.where((message) => message.chatId == chatId).length;
  }

  /// 获取用户单聊数量
  int getUserSingleChatCount(String userId) {
    return singleChats
        .where((chat) => chat.userId1 == userId || chat.userId2 == userId)
        .length;
  }

  /// 删除单聊
  @action
  bool deleteSingleChat(String chatId) {
    try {
      singleChats.removeWhere((chat) => chat.id == chatId);
      singleMessages.removeWhere((message) => message.chatId == chatId);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 获取单聊总数
  int get singleChatCount => singleChats.length;

  /// 获取消息总数
  int get messageCount => singleMessages.length;
}
